'''
A Twisted client for the asyncore time server protocol.

@author: Hatem Oraby
'''
import time
from twisted.internet import reactor, protocol

startTime = time.time()
print "AsciTime: " + time.asctime()
class TimeGrabber(protocol.Protocol):

    def dataReceived(self, data):
        TIME1970 = 2208988800L
        here = int(time.time()) + TIME1970
        print "Time delta: ", time.time() - startTime
        print "AsciTime: " + time.asctime()
        # get and unpack server time
        there = ord(data[3]) + (ord(data[2])<<8) \
                 + (ord(data[1])<<16) + (ord(data[0])<<24L)
        print "time difference is", int(here - there)
        #self.transport.loseConnection()
    
    def connectionLost(self, reason):
        print "connection lost"

class TGFactory(protocol.ClientFactory):
    protocol = TimeGrabber

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed - goodbye!"
        reactor.stop()
    
    def clientConnectionLost(self, connector, reason):
        print "Connection lost - goodbye!"
        reactor.stop()

def main():
    f = TGFactory()
    reactor.connectTCP("127.0.0.1", 8037, f)
    reactor.run()

if __name__ == '__main__':
    main()
